package gui;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import LogicSide.ManageSongPlaylist;
import LogicSide.ManageSongs;
import LogicSide.SongDetails;

public class MySongs {

	private static String selected_playlist = "";
	private static Table mySongsTable;
	private static TableItem selected_song_item = null;
	private static int song_id;
	private static int selection_index;

	/*
	 * public static void main (String [] args) { Display display = new Display
	 * (); Shell shell = new Shell (display); Combo combo = new Combo (shell,
	 * SWT.READ_ONLY); combo.setItems (new String [] {"Alpha", "Bravo",
	 * "Charlie"}); Rectangle clientArea = shell.getClientArea ();
	 * combo.setBounds (clientArea.x, clientArea.y, 200, 200); shell.pack ();
	 * shell.open (); while (!shell.isDisposed ()) { if
	 * (!display.readAndDispatch ()) display.sleep (); } display.dispose (); }
	 */

	public static Composite createMySongs(final Shell shell) {
		// update
		Main.inSearch = false;

		selected_playlist = "";
		selected_song_item = null;
		Composite mySongsComposite = new Composite(shell, SWT.BORDER);
		mySongsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));

		/**
		 * My song will hold two composite (1) the first for action over the
		 * songs (2) and the second for displaying my (user's) songs via a table
		 * 
		 * (1) contains : -add a selected song to playlist panel: -let's you
		 * choose a playlist -button for adding selected song -delete song (from
		 * My-Song list) - and a play now button to play a selected song
		 * 
		 * (2) is just a table containing all my songs
		 * 
		 */

		mySongsComposite.setLayout(new GridLayout(1, false));

		Composite controlComposite = new Composite(mySongsComposite, SWT.BORDER);
		controlComposite.setBackground(Display.getCurrent().getSystemColor(
				SWT.COLOR_MAGENTA));
		controlComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false,
				false, 1, 1));

		controlComposite.setLayout(new GridLayout(4, true));

		// Combo displaying playlists
		final Combo playlistsCombo = new Combo(controlComposite, SWT.READ_ONLY);
		playlistsCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));

		Display.getCurrent().asyncExec(new Runnable() {

			@Override
			public void run() {
				if(!playlistsCombo.isDisposed())
					fillPlaylistCombo(playlistsCombo);

			}
		});

		playlistsCombo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				int selection_index = playlistsCombo.getSelectionIndex();
				selected_playlist = playlistsCombo.getItem(selection_index);
				// DEBUG
				System.out.println(selected_playlist);
				//
			}
		});
		//
		// Add to playlist button
		Button addToPlaylistButton = new Button(controlComposite, SWT.PUSH
				| SWT.FLAT);
		addToPlaylistButton.setText("Add to playlist");
		addToPlaylistButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
				true, true, 1, 1));
		addToPlaylistButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				if (selected_playlist.isEmpty()) {
					Utils.popUpBox("Error", "Select a playlist first!", shell);
				} else if (selected_song_item == null) {
					Utils.popUpBox("Error", "Select a song!", shell);
				} else {
					new Thread(new Runnable() {
						public void run() {
							final boolean result = ManageSongPlaylist
									.addSongToPlaylist(song_id,
											selected_playlist, Main.session);
							Main.display.asyncExec(new Runnable() {

								@Override
								public void run() {
									if (result) {
										Utils.popUpBox("Success", "Done", shell);
									} else {
										Utils.popUpBox(
												"Failure",
												"Couldn't add song to playlist",
												shell);
									}

								}
							});
						}
					}).start();
				}

			}
		});
		//
		// Delete from my songs button
		Button deleteSongButton = new Button(controlComposite, SWT.PUSH
				| SWT.FLAT);
		deleteSongButton.setText("Delete song");
		deleteSongButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		deleteSongButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				if (selected_song_item == null)
					Utils.popUpBox("Error", "Select a song!", shell);
				else {
					new Thread(new Runnable() {
						public void run() {
							final boolean result = ManageSongs.deleteSong(
									song_id, Main.session);
							Main.display.asyncExec(new Runnable() {

								@Override
								public void run() {
									if (!result) {
										Utils.popUpBox("Success", "Done", shell);
										mySongsTable.remove(selection_index);
									} else {
										Utils.popUpBox("Failure",
												"Couldn't delete song", shell);
									}

								}
							});
						}
					}).start();
				}
			}
		});
		//
		// Playnow button
		Button playButton = new Button(controlComposite, SWT.PUSH | SWT.FLAT);
		playButton.setText("Play");
		playButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
				1, 1));
		playButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				if (selected_song_item != null) {
					final String song_name = selected_song_item.getText(1);
					new Thread(new Runnable() {
						@Override
						public void run() {
							final java.util.List<String> playlistSongs = new ArrayList<String>();
							playlistSongs.add(song_name);
							Main.display.asyncExec(new Runnable() {

								@Override
								public void run() {
									// remove current displaying panel
									Main.current.dispose();
									// update current displaying panel
									Main.current = PlayNow.createPlayNow(shell,
											playlistSongs);
									// needed for it to work
									shell.layout(true, true);

								}
							});

						}
					}).start();
				} else {
					Main.display.asyncExec(new Runnable() {
						public void run() {
							Utils.popUpBox("Error", "Select a song", shell);
						}
					});
				}
			}
		});
		//

		// Display song composite
		Composite displayComposite = new Composite(mySongsComposite, SWT.BORDER);
		displayComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		displayComposite.setBackground(Display.getCurrent().getSystemColor(
				SWT.COLOR_MAGENTA));
		displayComposite.setLayout(new GridLayout(1, true));

		// Table
		mySongsTable = new Table(displayComposite, SWT.MULTI | SWT.BORDER
				| SWT.FULL_SELECTION);
		mySongsTable.setLinesVisible(true);
		mySongsTable.setHeaderVisible(true);
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.heightHint = 200;
		mySongsTable.setLayoutData(data);
		mySongsTable.setBackground(Display.getCurrent().getSystemColor(
				SWT.COLOR_GRAY));

		final String[] titles = new String[] { "id", "Song", "Album", "Artist",
				"Year" };

		for (int i = 0; i < titles.length; i++) {
			TableColumn column = new TableColumn(mySongsTable, SWT.NONE);
			column.setText(titles[i]);
		}

		for (int i = 0; i < titles.length; i++) {
			mySongsTable.getColumn(i).pack();
		}
		Utils.loadingCursor(Main.display, shell);
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					final List<SongDetails> songs = ManageSongs
							.getAllUserSongs(Main.session);
					Main.display.asyncExec(new Runnable() {
						@Override
						public void run() {
							if (!mySongsTable.isDisposed()) {
								for (SongDetails sd : songs) {
									sd.fixNulls();
									TableItem item = new TableItem(
											mySongsTable, SWT.NONE);
									item.setText(Integer.toString(sd
											.getSong_id()));
									item.setText(1, sd.getSong_name());
									item.setText(2, sd.getAlbum_name());
									item.setText(3, sd.getArtist_name());
									item.setText(4,
											Integer.toString(sd.getYear()));
								}
								for (int i = 0; i < titles.length; i++) {
									mySongsTable.getColumn(i).pack();
								}
								Utils.regularCursor(Main.display, shell);
							}
							else{
								Utils.regularCursor(Main.display, shell);
							}
						}
					});
				} catch (SQLException e) {
					Main.display.asyncExec(new Runnable() {
						public void run() {
							Utils.popUpFailure(shell);
							Utils.regularCursor(Main.display, shell);
						}
					});
				}

			}
		}).start();
		//

		mySongsTable.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				selection_index = mySongsTable.getSelectionIndex();
				try {
					selected_song_item = mySongsTable.getItem(selection_index);
					song_id = Integer.parseInt(selected_song_item.getText());
				} catch (ArrayIndexOutOfBoundsException e) {
					selected_song_item = null;
					System.out.println("Boyng");
				}
			}
		});

		return mySongsComposite;
	}

	private static void fillPlaylistCombo(Combo playlistsCombo) {
		List<String> playlistsList = ManageSongPlaylist
				.getPlaylists(Main.session);
		String[] comboValues = new String[playlistsList.size()];
		for (int i = 0; i < comboValues.length; i++)
			comboValues[i] = playlistsList.get(i);
		playlistsCombo.setItems(comboValues);
	}
}
